<template>
  <div>
    <el-form :inline="true" class="demo-form-inline" :model="cateForm">
      <el-form-item label="一级分类">
        <el-select placeholder="请选择" v-model="cateForm.category1Id" @change="handler1" :disabled="show">
          <el-option :label="c1.name" :value="c1.id" v-for="c1 in list1" :key="c1.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select placeholder="请选择" v-model="cateForm.category2Id" @change="handler2" :disabled="show">
          <el-option :label="c2.name" :value="c2.id" v-for="c2 in list2" :key="c2.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择" v-model="cateForm.category3Id" @change="handler3" :disabled="show">
          <el-option :label="c3.name" :value="c3.id" v-for="c3 in list3" :key="c3.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'CategorySelect',
  data() {
    return {
      // 一级分类数据
      list1: [],
      list2: [],
      list3: [],
      // 各三级分类的id
      cateForm: {
        category1Id: '',
        category2Id: '',
        category3Id: '',
      },
    }
  },
  props: ['show'],
  mounted() {
    this.getCategory1List()
  },
  methods: {
    async getCategory1List() {
      let res = await this.$API.Attrs.reqCategory1List()
      if (res.code === 200) {
        this.list1 = res.data
      }
    },
    async handler1() {
      // 每次发请求都要清除上一次残留的数据
      this.list2 = []
      this.list3 = []
      this.cateForm.category2Id = ''
      this.cateForm.category3Id = ''
      const { category1Id } = this.cateForm
      let res = await this.$API.Attrs.reqCategory2List(category1Id)
      if (res.code === 200) {
        this.list2 = res.data
      }
    },
    async handler2() {
      this.list3 = []
      this.cateForm.category3Id = ''
      const { category2Id } = this.cateForm
      let res = await this.$API.Attrs.reqCategory3List(category2Id)
      if (res.code === 200) {
        this.list3 = res.data
      }
    },
    async handler3() {
      const { category1Id, category2Id, category3Id } = this.cateForm
      let res = await this.$API.Attrs.reqAttrList(category1Id, category2Id, category3Id)
      this.$emit('getAttrList', res.data, this.cateForm)
    },
  },
}
</script>

<style>
</style>